package com.quectel.util.common;

import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GlobalCoordinates;

import java.util.HashMap;
import java.util.Map;

/**
 * 距离计算
 *
 * @author caolu
 * @email louis.cao@quectel.com
 */
public class LocationUtils {

    /**
     * 单位米
     *
     * @param latitudeFrom
     * @param longitudeFrom
     * @param latitudeTo
     * @param longitudeTo
     * @return
     */
    public static double getDistance(double latitudeFrom, double longitudeFrom, double latitudeTo, double longitudeTo) {
        GlobalCoordinates source = new GlobalCoordinates(latitudeFrom, longitudeFrom);
        GlobalCoordinates target = new GlobalCoordinates(latitudeTo, longitudeTo);

        return new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, source, target).getEllipsoidalDistance();
    }

    /**
     * 单位米
     * 获取当前用户一定距离以内的经纬度值
     * return
     * 最小经度 minLng
     * 最小纬度 maxLat
     * 最大经度 maxLng
     * 最大纬度 minLat
     */
    public static Map<String, Double> getAround(double latitude, double longitude, double radius) {

        Map<String, Double> map = new HashMap<>();

        // 获取每度
        double degree = (24901 * 1609) / 360.0;

        double mpdLng = Double.parseDouble((degree * Math.cos(latitude * (Math.PI / 180)) + "").replace("-", ""));

        double dpmLng = 1 / mpdLng;
        double radiusLng = dpmLng * radius;
        //获取最小经度
        double minLat = longitude - radiusLng;
        // 获取最大经度
        double maxLat = longitude + radiusLng;

        double dpmLat = 1 / degree;
        double radiusLat = dpmLat * radius;
        // 获取最小纬度
        double minLng = latitude - radiusLat;
        // 获取最大纬度
        double maxLng = latitude + radiusLat;

        map.put("minLat", minLat);
        map.put("maxLat", maxLat);
        map.put("minLng", minLng);
        map.put("maxLng", maxLng);

        return map;
    }

    public static void main(String[] args) {
        Map<String, Double> around = getAround(50, 122, 1000);
        System.out.println(around);


        System.out.println(getDistance(50, 121.98602144847432, 50, 122));
        System.out.println(getDistance(50, 122.01397855152568, 50, 122));
        System.out.println(getDistance(49.99101476027792, 122, 50, 122));
        System.out.println(getDistance(50.00898523972208, 122, 50, 122));
    }
}
